package com.isman.placeslist;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.gson.Gson;
import com.isman.placeslist.apiobject.Status.Categories;
import com.isman.placeslist.util.GeoLocation;
import com.isman.placeslist.util.GeoLocation.LocationResult;
import com.isman.placeslist.util.Util;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PageNewPlace extends Activity {

	protected static final int FIND_CATEGORIES = 0;
	protected static final int GPS_DISABLE = 1;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_new_place);
		mInit();

		LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			mCreateGpsDisabledAlert();
		} else {
			progressDialog = ProgressDialog.show(this, "", "Finding location");
			progressDialog.setCancelable(true);
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					setResult(RESULT_CANCELED);
					finish();
				}
			});
			mGetLocation();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case GPS_DISABLE:
			LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
				mCreateNoGpsDeviceAlert();
			} else {
				progressDialog = ProgressDialog.show(this, "",
						"Finding location");
				progressDialog.setCancelable(true);
				progressDialog.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface arg0) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});
				mGetLocation();
			}
			break;
		}

	}

	protected void mInit() {
		vimgProfile = (ImageView) findViewById(R.id.img_newPlace_Profile);
		vlblPlace = (TextView) findViewById(R.id.lbl_newPlace_place);
		vetName = (EditText) findViewById(R.id.et_newPlace_name);
		vllBody = (LinearLayout) findViewById(R.id.ll_body);
		vibtnSend = (ImageButton) findViewById(R.id.ibtn_newstatus_send);
		vetDescription = (EditText) findViewById(R.id.et_newPlace_description);
		vspCategories = (Spinner) findViewById(R.id.sp_newPlace_categories);

		vllBody.setVisibility(View.GONE);
		vibtnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mNewPlace();
			}
		});
	}

	protected void mGetLocation() {
		GeoLocation geoLocation = new GeoLocation();
		geoLocation.getLocation(this, new LocationResult() {
			@Override
			public void gotLocation(Location location) {
				if (location != null) {
					mLatitude = location.getLatitude();
					mLongitude = location.getLongitude();
					mGetMapImage(location);
					mGetMapName(location);
					mGetCategories();
					vllBody.setVisibility(View.VISIBLE);
					progressDialog.dismiss();
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							progressDialog.dismiss();
							mCreateNoGpsDeviceAlert();
						}
					});
				}
			}
		});
	}

	protected void mCreateNoGpsDeviceAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("No device GPS, can not add new place.")
				.setCancelable(false)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	protected void mCreateGpsDisabledAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Your GPS is disabled! Would you like to enable it?")
				.setCancelable(false)
				.setPositiveButton("Enable GPS",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								mShowGpsOptions();
							}
						});
		builder.setNegativeButton("Do nothing",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	protected void mShowGpsOptions() {
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivityForResult(gpsOptionsIntent, GPS_DISABLE);
	}

	protected void mGetMapName(final Location location) {
		Geocoder gcd = new Geocoder(this, Locale.getDefault());

		try {
			List<Address> addresses = gcd.getFromLocation(
					location.getLatitude(), location.getLongitude(), 2);
			final StringBuilder sb = new StringBuilder();

			if (addresses.size() > 0) {
				Address addr = addresses.get(0);
				for (int i = 0; i < addr.getMaxAddressLineIndex(); i++) {
					sb.append(addr.getAddressLine(i) + " ");
				}
				mLocality = addr.getLocality();
				mSubLocality = addr.getSubLocality();
				mCountryName = addr.getCountryName();
				mCountryCode = addr.getCountryCode();
				mPostalCode = addr.getPostalCode();

				vlblPlace.setText(sb.toString());
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	protected void mGetMapImage(Location location) {
		final String mLink = "http://maps.googleapis.com/maps/api/staticmap?"
				+ "center="
				+ location.getLatitude()
				+ ","
				+ location.getLongitude()
				+ "&zoom=16&size=200x200"
				+ "&sensor=false"
				+
				// "&markers=icon:http://placeslist.com/pin.png"+
				// "&markers=color:red%7Clabel:G"+
				"&markers=icon:http://files.softicons.com/download/toolbar-icons/black-wireframe-toolbar-icons-by-gentleface/png/48/pin_map.png"
				+ "%7C" + location.getLatitude() + ","
				+ location.getLongitude();

		new Thread(new Runnable() {

			@Override
			public void run() {
				mImagePlace = Util.getBitmap(mLink);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						vimgProfile.setImageBitmap(mImagePlace);
					}
				});
			}
		}).run();

	}

	protected void mGetCategories() {
		ServiceProvider provider = new ServiceProvider(this);
		provider.GetPlaceCategories(new AsyncRunnerHeadler() {
			@Override
			public void onError(int statusCode, String json) {
				Log.e("Error", json);
			}

			@Override
			public void onConnectingError(String message) {
				Log.e("CError", message);

			}

			@Override
			public void onComplete(String json) {
				Log.e("Com", json);
				final Categories[] categories = new Gson().fromJson(json,
						Categories[].class);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						vspCategories.setAdapter(new MyList(categories));
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				Log.e("Auth", json);

			}
		});
	}

	protected void mNewPlace() {
		if (vetName.getText().toString().trim().length() > 4) {
			mNamePlace = vetName.getText().toString().trim();
			mDescription = vetDescription.getText().toString().trim();

		} else {
			vetName.setError("Request and name length 5");
			return;
		}
		progressDialog = ProgressDialog.show(this, "", "Created Place...");
		ServiceProvider provider = new ServiceProvider(this);
		provider.CreatePlace(mCategoriesId, mImagePlace, mNamePlace,
				mDescription, mLocality, mSubLocality, mCountryName,
				mCountryCode, mPostalCode, mLatitude, mLongitude,
				new AsyncRunnerHeadler() {

					@Override
					public void onComplete(String json) {
						Log.e("Complate", json);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								progressDialog.dismiss();
								Toast.makeText(PageNewPlace.this,
										"Create new place successful",
										Toast.LENGTH_LONG).show();
								startActivity(new Intent(PageNewPlace.this,
										PageMain.class));
							}
						});
					}

					@Override
					public void onAuthenticate(String json) {
						Log.e("Auth", json);
						progressDialog.dismiss();
					}

					@Override
					public void onError(int statusCode, String json) {
						Log.e("Error", json);
						progressDialog.dismiss();
					}

					@Override
					public void onConnectingError(String message) {
						Log.e("C Error", message);
						progressDialog.dismiss();
					}
				});
	}

	public class MyList extends BaseAdapter {

		Categories[] mCategories;

		public MyList(Categories[] categories) {
			// TODO Auto-generated constructor stub
			this.mCategories = categories;
		}

		@Override
		public int getCount() {
			return mCategories.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mCategories[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int index, View arg1, ViewGroup arg2) {
			final long id = mCategories[index].getId();
			TextView textView = new TextView(PageNewPlace.this);
			textView.setTextSize(16);
			textView.setHeight(72);
			textView.setGravity(Gravity.CENTER_VERTICAL);
			textView.setPadding(5, 0, 5, 0);
			textView.setText(mCategories[index].getName());
			textView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mCategoriesId = id;
				}
			});
			return textView;
		}
	}

	private String mNamePlace;
	private String mDescription;
	private String mLocality;
	private String mSubLocality;
	private String mCountryName;
	private String mCountryCode;
	private String mPostalCode;

	private Bitmap mImagePlace;
	private long mCategoriesId;
	private double mLatitude;
	private double mLongitude;

	private LinearLayout vllBody;
	private ImageView vibtnSend;
	private ImageView vimgProfile;
	private TextView vlblPlace;
	private EditText vetName;
	private Spinner vspCategories;
	private EditText vetDescription;
}
